import requests
from lxml import etree
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import os
import parsel
from selenium.webdriver.edge.options import Options

#创建文件夹
save_dir = '藏锋行'
if save_dir not in os.listdir('./'):
    os.mkdir(save_dir)


url = 'https://ac.qq.com/Comic/comicInfo/id/638544'
headers = {
    'User-Agent' : 'Mozilla/5.e (Windons NI 18.8; Winb4;x54)AppleWebkit/537.36(KHIML,like Gecko) Chrome/113.0.0.8 Safari/537.36', 'x-requested-with': 'XMLiIttpHequest',
}

response = requests.get(url=url,headers=headers)
response.encoding = response.apparent_encoding
selector = parsel.Selector(response.text)
href_list = selector.xpath('//span[@class="works-chapter-item"]/a/@href').getall()
#title_list = selector.xpath('//span[@class="works-chapter-item"]/a/@title').getall()
for herf  in list(reversed(href_list)):
    herf_data = 'https://ac.qq.com' + herf
    img_data = requests.get(url=herf_data,headers=headers).text
    selector_2 = parsel.Selector(img_data)
    title = selector_2.css('span.title-comicHeading::text').get()
    chapter_save_dir = os.path.join(save_dir, title)
    if title not in os.listdir(save_dir):
             os.mkdir(chapter_save_dir)
    #print(title)
    edge_options = Options()
    # 使用无头模式
    edge_options.add_argument('--headless')
    # 禁用GPU，防止无头模式出现莫名的BUG
    edge_options.add_argument('--disable-gpu')
    
    driver = webdriver.Edge(options=edge_options)

    driver.get(herf_data)
    targets =driver.find_elements(By.CSS_SELECTOR,'#comicContain > li > img')
    count = 0
    time.sleep(2)
    for target in targets:
        driver.execute_script("arguments[0].scrollIntoView()",target)
        time.sleep(3)
        img_url = target.get_attribute("src")
        #print(img_url)
        Name = '%03d.jpg' % (count + 1)
        pic_save_path = os.path.join(chapter_save_dir, Name)
        img_data = requests.get(url=img_url).content
        with open(pic_save_path  , mode='wb') as f:
            f.write(img_data)
            print('保存完成：', Name)
        count += 1
    driver.quit()
    
    
       
        







    